package com.steak.business.adapter;

import com.steak.business.client.OrderClient;
import com.steak.business.service.IBusinessService;
import com.steak.business.service.impl.BusinessServiceImpl;
import com.steak.common.domain.dataobject.tcc.Order;
import com.steak.common.domain.dto.PlaceOrderDTO;
import com.steak.common.result.Response;
import com.steak.common.tool.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.UUID;

/**
 * @author 刘牌
 * @date 2022/3/19:50
 */
@RestController
@AllArgsConstructor
public class PlaceOrderApi {

    private final IBusinessService businessService;
    private final OrderClient orderClient;

    @GlobalTransactional
    @PostMapping("placeOrder")
    public Response placeOrder(@RequestBody PlaceOrderDTO placeOrderDTO) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        int tryStatus = 1;
        Order order = buildOrder(placeOrderDTO, tryStatus);
        orderClient.saveOrder(order);
        Map<String, String> map = BeanUtils.describe(placeOrderDTO.setOrderId(order.getOrderId()));
        return businessService.placeOrder(map);
    }

    public Order buildOrder(PlaceOrderDTO placeOrderDTO , Integer status){
        return new Order()
                .setUserId(placeOrderDTO.getUserId())
                .setCommodityId(placeOrderDTO.getCommodityId())
                .setCount(placeOrderDTO.getCount())
                .setMoney(placeOrderDTO.getMoney())
                .setOrderId(IdWorker.fastId())
                .setStatus(status);
    }
}
